package main

import (
	"log"
	"os"
	"text/template"
)

func executeTemplate(text string, data interface{}) {
	parse, err := template.New("test").Parse(text)
	if err != nil {
		log.Fatal(err)
	}
	err = parse.Execute(os.Stdout, data)
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	tmpl, err := template.New("test").Parse("Template start\nAction: {{.}}\nTemplate end\n")
	if err != nil {
		log.Fatal(err)
	}
	err = tmpl.Execute(os.Stdout, true)
	err = tmpl.Execute(os.Stdout, "abc")
	err = tmpl.Execute(os.Stdout, 123)
	if err != nil {
		log.Fatal(err)
	}
	executeTemplate("Dot is: {{.}}!\n", 123.4)
	executeTemplate("Dot is: {{.}}!\n", "ABC")

	executeTemplate("start {{if .}}Dot is true!{{end}} finish\n", true)
	executeTemplate("start {{if .}}Dot is true!{{end}} finish\n", false)

	executeTemplate("Before loop: {{.}}\n{{range .}}In loop: {{.}}\n{{end}}After loop: {{.}}\n", []string{"do", "re", "mi", "la"})

	executeTemplate("Prices:\n{{range .}}${{.}}\n{{end}}", []float64{1.25, 0.99, 27})
	executeTemplate("Prices:\n{{range .}}${{.}}\n{{end}}", []float64{})
	executeTemplate("Prices:\n{{range .}}${{.}}\n{{end}}", nil)

	executeTemplate("Name: {{.Name}}\nRate: ${{.Rate}}\nActive: {{.Active}}\n", Subscriber{"zhang3", 66.66, true})
	executeTemplate("Name: {{.Name}}\n{{if .Active}}Rate: ${{.Rate}}\n{{end}}", Subscriber{"li4", 88.66, true})
}

type Subscriber struct {
	Name   string
	Rate   float64
	Active bool
}
